package com.lyfei.yd.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyfei.yd.common.exception.CustomException;
import com.lyfei.yd.system.domain.dto.CategoryDto;
import com.lyfei.yd.system.domain.dto.PageQueryDto;
import com.lyfei.yd.system.domain.entity.Category;
import com.lyfei.yd.system.mapper.CategoryMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("categoryService")
public class CategoryService extends BaseService<CategoryMapper, Category> {

    public void createCategory(CategoryDto dto) {
        Category category = new Category();
        BeanUtils.copyProperties(dto, category);
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());

        this.save(category);
    }

    public void updateCategory(CategoryDto dto, Long id) {
        Category category = this.getById(id);
        if (category == null) {
            throw new CustomException("分类不存在");
        }
        BeanUtils.copyProperties(dto, category);
        category.setUpdateTime(new Date());
        this.updateById(category);
    }


    public void deleteCategory(Long id) {
        Category category = this.getById(id);
        if (category == null) {
            throw new CustomException("分类不存在");
        }

        // 判断是否有子分类
        List<Category> subCategories = this.list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, id)
                .eq(Category::getDeleted, 0));

        if (!subCategories.isEmpty()) {
            throw new CustomException("该分类下存在子分类，无法删除");
        }

        this.removeById(id);
    }

    public IPage<Category> getCategoriesByPage(PageQueryDto pageQueryDto, boolean isRoot) {
        return this.page(new Page<>(pageQueryDto.getCurrent(), pageQueryDto.getPageSize()), new LambdaQueryWrapper<Category>()
                .eq(Category::getDeleted, 0)
                .eq(Category::getIsRoot, isRoot));
    }

    public IPage<Category> getSubCategoriesByPage(PageQueryDto pageQueryDto, Long parentId) {
        return this.page(new Page<>(pageQueryDto.getCurrent(), pageQueryDto.getPageSize()), new LambdaQueryWrapper<Category>()
                .eq(Category::getDeleted, 0)
                .eq(Category::getIsRoot, false)
                .eq(Category::getParentId, parentId));
    }

    public List<Category> getRootCategories() {
        return this.list(new LambdaQueryWrapper<Category>().eq(Category::getIsRoot, true).orderByAsc(Category::getIndex));
    }

    public List<Category> getAllSubCategories() {
        return this.list(new LambdaQueryWrapper<Category>().eq(Category::getIsRoot, false).orderByAsc(Category::getIndex));
    }
}
